package handler

import (
	"github.com/gin-gonic/gin"
	"onerk4/zg5yk/ordering/api/client"
	"onerk4/zg5yk/ordering/api/enit/request"
	"onerk4/zg5yk/ordering/api/enit/response"
	"onerk4/zg5yk/ordering/common/proto/order"
	"strconv"
)

func CreateOrder(c *gin.Context) {
	var req request.CreateOrder

	if err := c.ShouldBind(&req); err != nil {
		response.ErrorResponse(c, "参数错误", err.Error())
		return
	}

	userId := c.GetUint("userId")
	createOrder, err := client.CreateOrder(c, &order.CreateOrderRequest{
		UserId:    int64(userId),
		TakeoutId: req.TakeoutId,
		CouponId:  req.CouponId,
		Num:       int64(req.Num),
		Notes:     req.Notes,
	})
	if err != nil {
		response.ErrorResponse(c, "err", err.Error())
		return
	}

	response.SuccessResponse(c, "ok", createOrder)

}

func Callback(c *gin.Context) {
	orderSn := c.PostForm("out_trade_no")
	sta := c.PostForm("trade_status")

	if sta == "TRADE_FINISHED" {
		sta = "1"
	}

	if sta == "TRADE_SUCCESS" {
		sta = "2"
	}

	if sta == "WAIT_BUYER_PAY" {
		sta = "3"
	}

	if sta == "TRADE_CLOSED" {
		sta = "4"
	}

	status, _ := strconv.Atoi(sta)
	callback, err := client.Callback(c, &order.CallbackRequest{
		OrderSn: orderSn,
		Sta:     int64(status),
	})
	if err != nil {
		response.ErrorResponse(c, "err", err.Error())
		return
	}
	response.SuccessResponse(c, "ok", callback)
}

func ShowOrderList(c *gin.Context) {
	userId := c.GetUint("userId")
	list, err := client.ShowOrderList(c, &order.ShowOrderListRequest{
		UserId: int64(userId),
	})
	if err != nil {
		response.ErrorResponse(c, "err", err.Error())
		return
	}
	response.SuccessResponse(c, "ok", list)
}
